# 用SocketServer来改写ChatServer
import socketserver
import logging
import threading

FORMAT = "%(asctime)s %(threadName)s %(thread)s %(message)s"
logging.basicConfig(format=FORMAT,level=logging.INFO)


class ChatHandler(socketserver.BaseRequestHandler):
    clients = {} #保存客户端消息
    def setup(self):
        super().setup()
        self.event = threading.Event()
        print(self.client_address,threading.current_thread(),self.clients)

    def handle(self): #重写handle
        super().handle()
        # 一个客户端请求，一个request，一个handle实例
        while not self.event.is_set():
            try:
                data = self.request.recv(1024) #bytes，接收消息，服务端进程中与客户端通信用的Newsock
                # print(data, '+++++') #拿到消息后，打印下
                self.clients[self.client_address] = self.request
                msg = "%% {} %%".format(data.decode()).encode()
                # self.request.send(msg) #newsock给客户端发送消息
                for c in self.clients.values():
                    c.send(msg)
            except Exception as e:
                logging.info(e)
            logging.info(data)

            if data == 'quit':
                break



    def finish(self):
        super().finish()
        self.clients.pop(self.client_address)
        self.event.set() #离开时set


server = socketserver.ThreadingTCPServer(('127.0.0.1',9999),ChatHandler)  #多线程TCP，配置监听地址和端口，配置请求来的处理器
threading.Thread(target=server.serve_forever,name='server',daemon=True).start() #永久阻塞，将server扔到线程做
server.daemon_threads = True
# 这个daemon线程是源码中class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass提供的
# 其中class ThreadingMixIn定义类中有默认值daemon_threads = False


while True: #主线程做管理和观察
    cmd = input('>>>').strip()
    if cmd == 'quit':
        server.server_close() # 关闭
        break
    print(threading.enumerate())